<template>
    <div>
        <a-modal :keyboard="false" :maskClosable="false" title="工单移交" :open="visible" :width="800" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="12" :sm="12" :md="8">
                    <a-form layout="horizontal">
                        <a-form-item label="移交人">
                            <a-input placeholder="输入移交人" v-model:value="queryParams.orderChargePerson" allow-clear />
                        </a-form-item>
                    </a-form>
                </a-col>
                <a-col :xs="12" :sm="12" :md="8">
                    <a-form layout="horizontal">
                        <a-form-item label="工单编号">
                            <a-input placeholder="输入工单编号" v-model:value="queryParams.orderNum" allow-clear />
                        </a-form-item>
                    </a-form>
                </a-col>
                <a-col :xs="24" :sm="24" :md="12" :lg="8">
                    <a-button @click="handleSearch" type="primary">搜索</a-button>
                    <!-- <a-button @click="handleReset" class="ml-5px">重置</a-button> -->
                </a-col>
            </a-row>
            <a-table
                :size="state.tableSize"
                :loading="state.loading"
                :columns="dynamicColumns"
                :data-source="state.dataSource"
                :pagination="{
                    'show-size-changer': true,
                    current: state.current,
                    pageSize: state.pageSize,
                    total: state.total,
                    showTotal: total => `共 ${total} 条`,
                }"
                row-key="id"
                :row-selection="{ type: 'checkbox', selectedRowKeys: tableSelectedRowKeys, onChange: handleTableSelectChange }"
                :scroll="{ y: 300 }"
                @change="handleTableChange"
            >
                <template #bodyCell="{ record, column }">
                    <template v-if="column.dataIndex === 'org'">
                        <a-tooltip :content="[record.corpName, record.deptName, record.jobName].filter(Boolean).join('/')">
                            {{ [record.corpName, record.deptName, record.jobName].filter(Boolean).join('/') }}
                        </a-tooltip>
                    </template>
                </template>
            </a-table>
        </a-modal>

        <hand-on-select-user :visible="selectUserVisible" :model="tableSelectedRows" @success="handleSuccess" @cancel="selectUserVisible = false" />
    </div>
</template>

<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
import { Form } from 'ant-design-vue';
import { cloneDeep, isEmpty } from 'lodash-es';
import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
import { useFetchData } from '@/utils/hooks/useFetchData';
import { getOrderListToHandOn } from '@/api/order/mine-list';
import type { Pagination, TableColumn } from '@/typing';
import { message } from 'ant-design-vue';
import { statusMap as stateMap } from './common';
import HandOnSelectUser from './hand-on-select-user.vue';

type Key = string | number;

const baseColumns: TableColumn[] = [
    {
        title: '工单编号',
        dataIndex: 'orderNum',
    },
    {
        title: '工单状态',
        dataIndex: 'orderState',
        customRender: ({ text }) => stateMap[text],
    },
    {
        title: '项目名称',
        dataIndex: 'projectName',
        ellipsis: true,
    },
    {
        title: '当前负责人',
        dataIndex: 'orderChargePerson',
        ellipsis: true,
    },
];

export default defineComponent({
    props: {
        visible: {
            type: Boolean,
            required: true,
        },
        model: {
            type: Object as PropType<any>,
            default: () => null,
        },
    },
    emits: ['cancel', 'confirm'],
    setup(props, { emit }) {
        const loading = ref(false);
        const selectedKeys = ref<string[]>([]);
        const tableSelectedRowKeys = ref<Key[]>([]);
        const tableSelectedRows = ref<any[]>([]);
        const queryParams = reactive<any>({});
        const fetchDataContext = reactive<any>({
            current: 1,
            pageSize: 10,
            tableSize: 'middle', // 'default' | 'middle' | 'small'
            stripe: true,
            executeImmediately: false,
            isList: true,
            requestParams: { ...queryParams },
        });
        const { state: columnState, dynamicColumns, dynamicColumnItems } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
        const modelRef = reactive<any>({
            status: 1,
            projectCodes: [],
        });
        const rulesRef = reactive({
            code: [{ required: true, message: '请选择员工' }],
            roleIds: [{ required: true, message: '请选择角色' }],
            projectCodes: [{ required: true, message: '请设置负责项目' }],
        });
        const { validateInfos, resetFields } = Form.useForm(modelRef, rulesRef);
        // 表格数据和加载
        const { reload, context: state } = useFetchData(getOrderListToHandOn, fetchDataContext);

        const handleTableChange = ({ current, pageSize }: Pagination) => {
            // filteredInfoMap.value = filters;
            fetchDataContext.current = current;
            fetchDataContext.pageSize = pageSize;
        };

        const selectUserVisible = ref<boolean>(false);

        // 记录初始值
        const initValues = reactive({});
        watch(
            () => props.visible,
            () => {
                Object.assign(initValues, cloneDeep(props.model));
            },
        );
        watchEffect(() => {
            console.log(props.visible);
            if (props.visible) {
            }
        });

        const handleTableSelectChange = (selectedRowKeys: Key[], selectedRows: any[]) => {
            console.log(selectedRows, selectedRowKeys);

            tableSelectedRowKeys.value = selectedRowKeys;
            tableSelectedRows.value = selectedRows;
        };

        const handleCancel = () => {
            // resetFields();
            Object.keys(modelRef).forEach(key => {
                delete modelRef[key];
            });
            Object.keys(queryParams).forEach(key => {
                delete queryParams[key];
            });

            modelRef.projectCodes = [];
            modelRef.status = 1;
            emit('cancel');
        };

        const handleSubmit = async () => {
            if (!isEmpty(tableSelectedRowKeys.value)) {
                // const user = state.dataSource.find(item => tableSelectedRowKeys.value.includes(item.code));
                // emit('confirm', user);
                // tableSelectedRowKeys.value = [];
                selectUserVisible.value = true;
            } else {
                message.error('请选择工单');
            }
            // handleCancel();
        };

        const handleSearch = () => {
            fetchDataContext.current = 1;
            fetchDataContext.executeImmediately = true;
            fetchDataContext.requestParams = { ...queryParams };
        };
        const handleReset = () => {
            queryParams.keyword = '';
            fetchDataContext.current = 1;
            fetchDataContext.requestParams = { ...queryParams };
        };

        const handleSuccess = () => {
            selectUserVisible.value = false;
            handleCancel();
        };
        return {
            loading,

            reload,
            state,
            columnState,
            dynamicColumns,
            dynamicColumnItems,

            modelRef,
            validateInfos,
            resetFields,

            handleSubmit,
            handleCancel,

            initValues,

            selectedKeys,
            tableSelectedRowKeys,

            handleTableChange,

            handleTableSelectChange,
            handleSearch,
            handleReset,
            queryParams,

            selectUserVisible,

            tableSelectedRows,

            handleSuccess,
        };
    },
    components: {
        HandOnSelectUser,
    },
});
</script>

<style lang="less" scoped></style>
